<?php
	class LoginHandler
	{
		// Membervariables
		private $_userHandler = null;
		
		// Constants
		const LOGOUTMESSAGE = "You're logged out";
		const LOGINMESSAGE = "You're logged in";
		const LOGINERRORMESSAGE = "Wrong username or password";
		const ISLOGGEDIN = "uniksessionsId";
		
		public function __construct(\UserHandler $userhandler)
		{
			$this->_userHandler = $userhandler;
		}
		
		// Function that handles Loging out.
		public function DoLogout()
		{
			$_SESSION[LoginHandler::ISLOGGEDIN] = false;
		}
		
		// Function that handles Loging in.
		public function DoLogin($username, $password)
		{
			$username = trim($username);
			$password = trim($password);
			
			// Check if the username exists.
			$user = $this->_userHandler->GetUser($username);
			
			// If it does, get the password... 
			if ($user != null)
			{
				$pass = $user->password;
				
				// Add the salt to the password input and encrypt it to match it against the saved password.
				$password = $password . $user->salt;
				
				$password = $this->_userHandler->Encrypt($password);

				// Check if the user-input matches the users password.
				if ($password == $pass)
				{
					$_SESSION[LoginHandler::ISLOGGEDIN] = true;
				}
				else
				{
					$_SESSION[LoginHandler::ISLOGGEDIN] = false;	
				}
			}
		}
		
		// Function that returns wether you're logged in or not.
		public function IsLoggedIn()
		{
			if (isset($_SESSION[LoginHandler::ISLOGGEDIN]) == true && $_SESSION[LoginHandler::ISLOGGEDIN] == true)
			{
				return true;
			}
			
			return false;
		}
	}